package com.sen.uaa.config;

import com.sen.uaa.exception.BootOauth2WebResponseExceptionTranslator;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.annotation.Resource;

/**
 * @author esJiang
 */
@Configuration
@EnableAuthorizationServer
public class OauthServerConfig extends AuthorizationServerConfigurerAdapter {

    /**
     * 密码模式必须需要
     */
    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private ClientDetailsService clientDetailsService;

    @Resource
    private BootOauth2WebResponseExceptionTranslator bootOAuth2WebResponseExceptionTranslator ;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService) ;
    }

    @Resource
    private TokenStore tokenStore ;

    @Resource
    private TokenGranter tokenGranter ;

    @Resource
    private UserDetailsService userDetailsService;

    /**
     *  配置令牌信息，如需要支持密码模式，必须要有：authenticationManager(authenticationManager)
     **/
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.tokenStore(tokenStore).authenticationManager(authenticationManager)
        .userDetailsService(userDetailsService);
        /**异常处理 **/
        endpoints.exceptionTranslator(bootOAuth2WebResponseExceptionTranslator) ;
        endpoints.tokenGranter(tokenGranter) ;
    }


    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer.tokenKeyAccess("isAuthenticated()").checkTokenAccess("permitAll()");
        oauthServer.allowFormAuthenticationForClients();//支持客户端模式登录
    }
}
